import { onLoad } from "@dcloudio/uni-app"

export function freshLoading() {
	const offset = ref<number>(0)
	const limit = ref<number>(10)
	const listCount = ref<number>(0)
	const listData = ref<any[]>([])
	const triggered = ref<boolean>(false)
	const isLoadingMore = ref<boolean>(false)
	const freshing = ref<boolean>(false)
	const searched = ref<boolean>(false)
	const listService = ref<any>(null)
	const updateListParams = ref<Function>(() => {
		return {}
	})
	const transformListData = ref<Function>((data: any) => {
		return data
	})
	const getListSuccessCallback = ref<Function>(() => {})
	const getListFailedCallback = ref<Function>(() => {})
	const beforeGetListData = ref<Function>(() => {})

	onLoad(() => {
		freshing.value = false
		triggered.value = false
		searched.value = false
	})
	function initRefreshStatus() {
		triggered.value = false
		freshing.value = false
		isLoadingMore.value = false
	}
	function initList() {
		offset.value = 0
		limit.value = 10
		listCount.value = 0
		listData.value = []
		isLoadingMore.value = false
	}
	function onPulling(e: any) {
		if (e.detail.deltaY < 0) {
			return
		}
		triggered.value = true
	}
	function onRefresh() {
		console.log("on refresh")
		// if (!preventPreviewImageLoad()) {
		// 	return
		// }

		if (freshing.value) {
			return
		}
		freshing.value = true
		getListData(true)
	}
	function onRestore() {
		triggered.value = "restore" as any // 需要重置
		console.log("onRestore")
	}
	function onAbort() {
		console.log("onAbort")
	}

	function getListData(needReset?: boolean) {
		if (isLoadingMore.value) {
			return
		}
		isLoadingMore.value = true

		if (needReset) {
			//重置后获取
			initList()
		}

		const postParams = Object.assign({}, updateListParams.value(), {
			offset: offset.value,
			limit: limit.value,
		})

		beforeGetListData.value()
		if (!listService.value) {
			return
		}
		searched.value = false
		listService
			.value(postParams)
			.then((data: any) => {
				if (!data) {
					return
				}
				listCount.value = data.count
				listData.value = listData.value.concat(transformListData.value(data.list))
				initRefreshStatus()
				searched.value = true
				getListSuccessCallback.value()
			})
			.catch(() => {
				initRefreshStatus()
				getListFailedCallback.value()
			})
	}
	function loadMore() {
		if (listData.value.length < listCount.value) {
			offset.value = offset.value + limit.value
			getListData()
		}
	}

	return {
		triggered,
		listService,
		listData,
		updateListParams,
		getListSuccessCallback,
		getListFailedCallback,
		beforeGetListData,
		transformListData,
		initRefreshStatus,
		initList,
		onPulling,
		onRefresh,
		onRestore,
		onAbort,
		getListData,
		loadMore,
		freshing,
		searched,
	}
}
